<template xmlns:https="http://www.w3.org/1999/xhtml" xmlns:https="http://www.w3.org/1999/xhtml"
          xmlns:https="http://www.w3.org/1999/xhtml" xmlns:https="http://www.w3.org/1999/xhtml"
          xmlns:https="http://www.w3.org/1999/xhtml" xmlns:https="http://www.w3.org/1999/xhtml"
          xmlns:https="http://www.w3.org/1999/xhtml" xmlns:https="http://www.w3.org/1999/xhtml">
  <div style="display: flex">
    <div style="margin-top: 10px">
      <i class="el-icon-arrow-left" @click="fanhui"></i>
      <div>
        <span>搜索地址：</span>
        <el-autocomplete
          v-model="keywords"
          style="width: 300px"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
        <span style="margin-left: 10px">
        </span>
        <el-button style="margin-left: 10px" type="danger" size="small" @click="reset">清空</el-button>
      </div>
      <div id="container" class="container"></div>
      <div id="panel"></div>
    </div>
    <div id="under" style="margin-top: 100px">
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "23a30393a855e07d2ba7621ac8e4e6d2",
};
export default {
  name: "HomeView",
  data() {
    return {
      // 地图实例
      map: null,
      toolbar: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      //缩放控件
      ToolBar: null,
      //地图放大镜
      HawkEye: null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      form: {
        lng: "116.208741",
        lat: "40.136902",
        address: '',
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      trackPositions: [],
      //精准定位
      Geolocation() {
      },

      driverTime: null,
      driverLong: null,
      startaddress: "",
      endaddress: "",
      // 开始的经纬度
      startLatitudeAndLongitude: "116.379028, 39.865042",
      // 结束的经纬度
      endLatitudeAndLongitude: "116.427281, 39.803719",
    };
  },
  created() {

  },
  methods: {
    async getMapApi() {
      if (this.trackPositions && this.trackPositions.length) {
        // 通过 高德 API获取 all 所有 路线 经纬度
        //构造路线导航类
        var driving = new AMap.Driving({
          map: this.map,
          panel: "panel"
        });
        var lngsrt = this.trackPositions[0];
        // 根据起终点经纬度规划驾车导航路线
        driving.search(
          new AMap.LngLat(this.trackPositions[0][0], this.trackPositions[0][1]),
          new AMap.LngLat(this.trackPositions[1][0], this.trackPositions[1][1]),
          function (status, result) {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考
            // https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
              // this.map.setFitView();
              console.log('绘制驾车路线完成')
            } else {
              console.log('获取驾车数据失败：' + result)
            }
          })
      }
    },
    fanhui(){
      this.$router.push("/shouye")
    },
    reset() {
      this.keywords = '';
      this.form = {
        lng: "116.208741",
        lat: "40.136902",
        address: '',
      }
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    },
    initMap() {
      let that = this;
      AMapLoader.load({
        // 你申请的Key
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder",
          "AMap.AutoComplete", "" +
          "AMap.ToolBar",
          "AMap.HawkEye",
          "AMap.Geolocation",
          "AMap.Driving",
          "AMap.PlaceSearch"
        ],
      }).then((AMap) => {
        that.map = new AMap.Map("container", {
          viewMode: "3D", //是否为3D地图模式
          zoom: 23, //初始化地图级别
          center: [that.form.lng, that.form.lat], //初始化地图中心点位置
        });
        //地址逆解析插件
        that.geoCoder = new AMap.Geocoder({
          city: "北京", //城市设为北京，默认：“全国”
          radius: 1000, //范围，默认：500
        });
        // 搜索提示插件
        that.AutoComplete = new AMap.AutoComplete({
          city: "北京",
          citylimit: true,
          radius: 1000 // 设置搜索半径为1000米，你可根据实际需求调整
        });
        that.ToolBar = new AMap.ToolBar({
          position: {
            bottom: '210px',
            right: '35px'
          }
        });
        that.HawkEye = new AMap.HawkEye({
          position: {
            // bottom: '110px',
            // left: '35px'
          }
        });
        that.Geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认：true
          timeout: 10000, // 设置定位超时时间，默认：无穷大
          offset: [10, 20],  // 定位按钮的停靠位置的偏移量
          zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          citylimit: true,  //是否强制限制在设置的城市内搜索
          position: 'RB' //  定位按钮的排放位置,  RB表示右下

        });
        that.map.addControl(that.ToolBar);
        that.map.addControl(that.HawkEye);
        that.map.addControl(that.Geolocation);
        // 清除点
        that.removeMarker();
        // 标记点
        that.setMapMarker();
        //点击获取经纬度;
        that.map.on("click", (e) => {
          // 获取经纬度
          that.form.lng = e.lnglat.lng;
          that.form.lat = e.lnglat.lat;
          // 清除点
          that.removeMarker();
          // 标记点
          that.setMapMarker();
        });
      })
        .catch((err) => {
          // 错误
        });
    },
    // 标记点
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      // 逆解析地址
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    // 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress;
        } else {
          this.form.address = '';
        }
      });
    },
    querySearchAsync(queryString, cb) {
      if (queryString) {
        // 获取当前位置经纬度
        const currentLngLat = new AMap.LngLat(this.form.lng, this.form.lat);
        // 使用AMap.PlaceSearch进行附近位置搜索
        const placeSearch = new AMap.PlaceSearch({
          map: this.map,
          radius: 1000, // 使用之前设置的搜索半径
          extensions: 'all'
        });
        placeSearch.searchNearBy(queryString, currentLngLat, (status, result) => {
          if (status === 'complete') {
            this.options = result.poiList.pois;
            for (let i = 0; i < this.options.length; i++) {
              this.options[i].value = this.options[i].name;
            }
          } else {
            this.options = [];
          }
          cb(this.options);
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },
    handleSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      this.trackPositions = [];
      this.trackPositions.push([this.form.lng, this.form.lat]);
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
      };
      this.trackPositions.push([this.form.lng, this.form.lat])
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
      // 绘画地图
      this.getMapApi(this.trackPositions);
    },
  },
  mounted() {
    this.initMap();

  },
  unmounted() {
    this.map.destroy();
  },

};
</script>

<style scoped>
.container {
  margin-top: 10px;
  width: 400px;
  height: 700px;
}

</style>
